//
//  JQFXHBenddAPI.swift
//  jiuzhoudai
//
//  Created by zhaochengfeng on 2025/7/9.
//


import Foundation
import Moya
import CryptoKit
import SwiftyJSON


protocol JQFXHThirdErrorqqParams {
    func mobile() -> String
    var params: [String: Any] { get }
    func jqfxhErrorrrCode(json: JSON) -> Int
    func jqfxhErrorssMsg(json: JSON) -> String
    func jqfxhIsqqError(json: JSON) -> Bool
}

// 定义 API 请求的 Target
enum JQFXHBenddAPI {
    case jqfxhServicehhInfo
    case jqfxhCheckiiMobile(mobile: String)
    case setPassjjword(password: String)
    case jqfxhSendkkSMS(mobile: String)
    case jqfxhLllogin(mobile: String, code: String, password: String, type: Int)
    case jqfxhLoanmApply(dic: [String: String])
    case jqfxhFeednnBack(contentStr: String)
    case jqfxhThirdFeedooBack(contentStr: String)
    case jqfxhLogppoff
    case jqfxhThirdLogqqoff
    case jqfxhAbnormannl(para:Dictionary<String, Any>, request: String, mobile: String, code: Int)
    case jqfxhReporoot(loginStatus:String, formStatus: String)
    
}

// 实现 Moya 的 TargetType 协议
extension JQFXHBenddAPI: TargetType {

    var baseURL: URL {
        return URL(string: JQFXHCompanyMessage.jqfxhBaseUrl)!
    }
    
    var path: String {
        switch self {
        case .jqfxhServicehhInfo:
            return "/api/servers"
        case .jqfxhCheckiiMobile(_):
            return "/api/v1/user/getMobileInfo"
        case .jqfxhSendkkSMS(_):
            return "/api/v1/user/sendSms"
        case .jqfxhLllogin(_, _, _, _):
            return "/api/v1/user/login"
        case .jqfxhLoanmApply(_):
            return "/api/v1/apply/apply"
        case .jqfxhFeednnBack(_):
            return "/api/v1/feedback/feedback"
        case .jqfxhThirdFeedooBack(_):
            return "/api/partner/feedback/feedback"
        case .setPassjjword(_):
            return "/api/v1/user/setPasswd"
        case .jqfxhLogppoff:
            return "/api/v1/user/logoff"
        case .jqfxhThirdLogqqoff:
            return "/api/partner/user/logoff"
        case .jqfxhAbnormannl(_, _, _, _):
            return "/api/partner/report/abnormal"
        case .jqfxhReporoot(_, _):
            return "/api/partner/report/report"
        }
    }
        
    
    var task: Task {
        .requestParameters(parameters: parameters, encoding: method == .get ? URLEncoding.default : JSONEncoding.default)
    }

    func jdqhGetJsonString(dict:[String : Any]) -> String {
        if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) {
            var jsonString = String(data: jsonData, encoding: .utf8)
            jsonString = jsonString?.replacingOccurrences(of: "\\", with: "")
            return jsonString ?? ""
        }
        return ""
    }
            
    var parameters: [String: Any] {
        switch self {
        case .jqfxhServicehhInfo:
            return [:]
        case .jqfxhCheckiiMobile(mobile: let mobile):
            return ["mobile": mobile]
        case .jqfxhSendkkSMS(let mobile):
            return ["mobile": mobile, "event": "login"]
        case .jqfxhLllogin(mobile: let mobile, code: let code,password: let password,type: let type):
            return ["mobile": mobile, "code": code, "password": password, "type": type]
        case .jqfxhLoanmApply(dic: let para):
            return para
        case .jqfxhFeednnBack(let contentStr):
            return ["content": contentStr]
        case .jqfxhThirdFeedooBack(let contentStr):
            return ["content": contentStr, "partner_id":JQFXHNetworkManager.shared.partnerId, "mobile":JQFXHNetworkManager.shared.jqfxhCurrentUser?.mobile as Any]
        case .setPassjjword(password: let password):
            return ["password": password]
        case .jqfxhLogppoff:
            return [:]
        case .jqfxhThirdLogqqoff:
            return ["partner_id":JQFXHNetworkManager.shared.partnerId, "mobile":JQFXHNetworkManager.shared.jqfxhCurrentUser?.mobile as Any]
        case .jqfxhAbnormannl(para: let para, request: let request, mobile: let mobile, code: let code):
            var mobileStr = mobile
            if mobileStr.count == 0 {
                mobileStr = JQFXHNetworkManager.shared.jqfxhCurrentUser?.mobile ?? ""
            }
            var params = para["params"] as? String ?? ""
            let result = para["result"] as? String ?? ""
            params = params.replacingOccurrences(of: "\\", with: "")
            var paramsDic : [String : Any] = [:]
            var resultDic : [String : Any] = [:]
            if let jsonData = params.data(using: .utf8) {
                do {
                    if let dict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                        paramsDic = dict
                    }
                } catch {
                }
            }
            if let jsonData1 = result.data(using: .utf8) {
                do {
                    if let dict1 = try JSONSerialization.jsonObject(with: jsonData1, options: []) as? [String: Any] {
                        resultDic = dict1
                    }
                } catch {
                }
            }
            let dic = ["name" : "", "request": request, "param": paramsDic, "result": resultDic] as [String : Any]
            let paras = ["mobile":mobileStr, "code": code, "msg": self.jdqhGetJsonString(dict: dic)] as [String : Any]
            return paras
        case .jqfxhReporoot(let loginStatus, let loanStatus):
            return ["partner_id":JQFXHNetworkManager.shared.partnerId, "mobile":JQFXHNetworkManager.shared.jqfxhCurrentUser?.mobile as Any, "login_status":loginStatus, "form_status": loanStatus]
        }
    }


    
    var method: Moya.Method {
        switch self {
        case .jqfxhServicehhInfo:
            return .get
        case .jqfxhCheckiiMobile(_):
            return .get
        default:
            return .post
            
        }
    }
    
        
    var headers: [String: String]? {
        
        
        let time = String(format: "%.0f", Date().timeIntervalSince1970)
        let customUUID = JQFXHDeviceIdenlltifier.jqfxhGetCustommmUUID()
        var header = ["t": time, "v": JQFXHCompanyMessage.jqfxhVersion,"appid": JQFXHCompanyMessage.jqfxhAppId,"imei": time, "imsi": customUUID, "storeid": "15"]
        
        var strings: [String] = []
        header.keys.sorted().forEach { key in
            if let value = header[key] {
                strings.append(key + "=" + value)
            }
        }
        let payloadWithSecret = strings.joined(separator: "&") + "shanshuilanwei"
        let firstMD5 = JQFXHNetworkManager.shared.md5(payloadWithSecret)
        let secondMD5 = JQFXHNetworkManager.shared.md5(firstMD5)
        header["channel"] = "15"
        header["x-head-signature"] = secondMD5
        if let user = JQFXHNetworkManager.shared.jqfxhCurrentUser, !user.token.isEmpty {
            header["token"] = user.token
        }
                
        return header
        
    }
    
}
